<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="70px">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="关键字">
                <el-input v-model="query.keyword" aria-placeholder="模糊搜索"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="名称">
                <el-input v-model="query.name" aria-placeholder="模糊搜索"></el-input>
              </el-form-item>
            </el-col>788
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <rrOperation :crud="crud"/>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <crudOperation :permission="permission">
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form size="small" label-width="70px">
          <el-form-item label="编码">
            <el-input v-model="form.code"></el-input>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="路径">
            <el-input v-model="form.path" ></el-input>
          </el-form-item>
          <el-form-item label="人员">
            <zSelect :value.sync="form.userId" :label="form.userName" url="api/dropDown/sysUserList" :params="{businessAttr:'3'}"
                     style="width:  100%"/>
          </el-form-item>
        </el-form>
        <el-button @click="() => append()" style="margin: 10px 0">添加</el-button>
        <el-tree
          class="treeitems"
          :data="form.content"
          node-key="id"
          border
          draggable
          default-expand-all
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
          @node-drag-start="handleDragStart"
          @node-drag-enter="handleDragEnter"
          @node-drag-leave="handleDragLeave"
          @node-drag-over="handleDragOver"
          @node-drag-end="handleDragEnd"
          @node-drop="handleDrop"
          ref="tree"
        >
     <span class="custom-tree-node" slot-scope="{ node, data }">
       <span>{{ node.label }}</span>
       <span>
<!--         <i @click="() => append(node,data)" class="el-icon-plus"></i>&lt;!&ndash;增加分组&ndash;&gt;-->
         <!-- 根节点不需要删除和重命名 -->
         <i @click="() => remove(node,data)" class="el-icon-delete"></i><!--删除分组-->
         <i @click="() => rename(node,data)" class="el-icon-edit"></i><!--重命名分组-->
       </span>
     </span>
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="submitCU">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="操作"
        :visible.sync="centerDialogVisible"
        width="50%">
        <el-form ref="form" :model="addForm" label-width="80px">
          <el-form-item label="名称">
            <el-input v-model="addForm.label"></el-input>
          </el-form-item>
          <el-form-item label="字段名称">
            <el-input v-model="addForm.prop"></el-input>
          </el-form-item>
          <el-form-item label="添加类型">
            <el-select v-model="addForm.type"  style="width: 100%" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否显示">
            <el-select v-model="addForm.visible"  style="width: 100%" placeholder="请选择">
              <el-option
                v-for="item in  showOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="宽度">
            <el-input-number v-model="addForm.width"></el-input-number>
          </el-form-item>
          <el-form-item label="字典名称" v-if="addForm.type == 3" >
            <el-input  v-model="addForm.dictionary" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addName(addForm)">确 定</el-button>
        </span>
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table" stripe border v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
        <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('code')" prop="code" label="编码" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('name')" prop="name" label="名称" />
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('type')" prop="type" label="类型(1:默认)" />-->
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('path')" prop="path" label="路径url" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('content')" prop="content" label="内容" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('userCode')" prop="userCode" label="人员编码" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('userName')" prop="userName" label="人员名称" />
        <el-table-column :render-header="crud.renderHeader" v-permission="['admin','headerProperties:edit','headerProperties:del']" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudHeaderProperties from '@/api/erp/headerProperties'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { initDataPlus } from '@/api/data'
import crudBasSaleSystem from '@/api/erp/salesOrder'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '表头属性', url: 'api/headerPropertiesConfig', sort: 'id,desc',optShow: {
    add: true,
    edit: true,
    del: true,
    download: false,
    leadingIn: false,
    enable: false,
    disable: false,
    reject: false,
    pass: false
  }, crudMethod: { ...crudHeaderProperties }})
const defaultForm = { id: null, code: null, name: null, type: null, path: null, content: [], userId: null, userCode: null, userName: null }
export default {
  name: 'HeaderProperties',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      permission: {
        add: ['admin', 'headerProperties:add'],
        edit: ['admin', 'headerProperties:edit'],
        del: ['admin', 'headerProperties:del'],
        import: ['admin', 'headerProperties:import'],
        export: ['admin', 'headerProperties:export'],
        copy: ['admin', 'headerProperties:copy'],
        upload: ['admin', 'headerProperties:upload'],
        download: ['admin', 'headerProperties:download'],
      },
      centerDialogVisible:false,
      addForm:{
        label: null,
        type: null,
        dictionary: null,
        isAdd: true,
        prop: null,
        visible:true,
        width: 100
      },
      options: [{
        value: '1',
        label: '普通'
      }, {
        value: '2',
        label: '时间'
      }, {
        value: '3',
        label: '字典'
      }, {
        value: '4',
        label: '自定义'
      }],
      showOption: [{
        value: true,
        label: '是'
      }, {
        value: false,
        label: '否'
      }],
      showIndex:0,
      rules: {
      }    }
  },
  watch: {
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      console.log('content', JSON.parse(form.content))
      this.form.content = JSON.parse(form.content)
    },
    submitCU(){
      const data = {
        name: this.form.name,
        code:  this.form.code,
        path: this.form.path,
        userId: this.form.userId,
        content: JSON.stringify(this.form.content)
      }
      crudHeaderProperties.update(data).then(res => {
        this.centerDialogVisible = false
        this.$message.success("保存成功")
        this.crud.cancelCU()
        this.crud.toQuery()
      }).catch((res)=>{
      })
    },
    rename(node,data) {
      this.form.content.map((res,index)=>{
        if(res.label == data.label){
          this.showIndex = index
        }
      })
      console.log('rename',this.showIndex)
      console.log('this.centerDialogVisible = true', node,data)
      this.addForm.label = data.label
      this.addForm.type = data.type
      this.addForm.prop = data.prop
      this.addForm.visible = data.visible
      this.addForm.width = data.width
      this.addForm.isAdd = false
      this.addForm.dictionary = data.dictionary
      this.centerDialogVisible = true
      // console.log(node,data.$treeNodeId,'修改')
      // this.$prompt('节点名字', '修改节点', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   inputPattern: /^[\u4e00-\u9fa5]{0,}$/,//匹配全中文
      //   inputErrorMessage: '请输入中文'//不符合正则匹配的提示语句
      // }).then(({ value }) => {
      //   this.form.content[data.$treeNodeId-1].label = value
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '取消修改'
      //   });
      // });
    },
    handleDragStart(node, ev) {
    },
    handleDragEnter(draggingNode, dropNode, ev) {
    },
    handleDragLeave(draggingNode, dropNode, ev) {
    },
    handleDragOver(draggingNode, dropNode, ev) {
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      // this.crud.toUpdateHeader()
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // this.crud.toUpdateHeader()
    },
    allowDrop(draggingNode, dropNode, type) {
      if (type !== 'inner') {
        return true
      }
    },
    allowDrag(draggingNode) {
      return draggingNode.data.label.indexOf('三级 3-2-2') === -1
    },
    addName(form){
      if(!form.isAdd){
        this.form.content[this.showIndex].dictionary = this.addForm.dictionary
        this.form.content[this.showIndex].label = this.addForm.label
        this.form.content[this.showIndex].prop = this.addForm.prop
        this.form.content[this.showIndex].type = this.addForm.type
        console.log(this.form.content[this.showIndex].type)
        this.form.content[this.showIndex].visible = this.addForm.visible
        this.form.content[this.showIndex].width = this.addForm.width
      }else{
        this.form.content.push({
          dictionary: this.addForm.dictionary,
          isSelected: false,
          id: null,
          label: this.addForm.label,
          prop: this.addForm.prop,
          type: this.addForm.type,
          isAdd: true,
          visible: true,
          width: 100
        });
      }
      this.centerDialogVisible = false
    },
    //点重命名事件
    append() {
      this.addForm = {
        dictionary: "",
        isSelected: false,
        id: null,
        label: "",
        prop: "",
        type: "1",
        isAdd: true,
        visible: true,
        width: 100
      }
      this.centerDialogVisible = true
      // this.$prompt('节点名字', '增加节点', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   inputPattern: /^[\u4e00-\u9fa5]{0,}$/,//匹配全中文
      //   inputErrorMessage: '请输入中文'//不符合正则匹配的提示语句
      // }).then(({ value }) => {
      // //   this.form.content.splice(data.$treeNodeId, 0,{
      // //     isSelected:'false',
      // //     label: value,
      // //     prop: "id",
      // //     visible: true,
      // //     width: 100,
      // //     $treeNodeId: data.$treeNodeId +1
      // // });
      //   this.form.content.push({
      //     isSelected:'false',
      //     label: value,
      //     prop: "id",
      //     visible: true,
      //     width: 100,
      //     $treeNodeId: this.form.content.length +1
      //   })
      //   console.log('this.form.content',this.form.content,data.$treeNodeId)
      //   //可以在这里发请求，http是我模拟的一个虚假的封装好的axios请求,()可写请求参数
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '取消修改'
      //   });
      // });
    },
    //实现局部刷新，在点击弹窗处调用的
    partialRefreshpartialRefresh(node){
      //设置loaded为false；模拟一次节点展开事件，加载重命名后的新数据；
      node.loaded = false;
      node.expand();
      //新建子节点是刷新一次本节点的展开请求，而重命名和删除则需要刷新父级节点的的展开事件，
      //可以设置node.parent.loaded = false;node.parent.expand();
    },
    doLeadingIn() {
      this.importStatus = true
    },
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.prop === data.prop);
      children.splice(index, 1);
    },

  }
}
</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
  .tree_container{
    height: 500px;
    border-radius: 5px;
    background-color: rgba(1,28,82,.5);
  }
  .el-tree{
    background: transparent;
    color: #000000;
  /*改变高度*/
  .el-tree-node__content{
    height: 50px;
  }
  /*tree组件选中背景色修改 */
  .el-tree-node.is-current > .el-tree-node__content{
    background-color: rgba(1,68,144,.5);
  }
  /*tree组件鼠标hover悬浮背景色 */
  .el-tree-node > .el-tree-node__content:hover{
    background-color: rgba(1,68,144,.5);
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 20px;
  }
  }
</style>
